package com.hsource.healthcenter.controller;

import com.alibaba.fastjson.JSONObject;
import com.hsource.common.utils.CommonResp;
import com.hsource.common.utils.DateUtil;
import com.hsource.common.utils.resultUtils.controller.BaseController;
import com.hsource.healthcenter.util.ServletUtils;
import com.hsource.healthcenter.util.StringUtils;
import com.hsource.healthcenter.util.aliyunApiHttp.HttpUtils;
import com.hsource.healthcenter.util.http.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author yangYang
 * @version 1.0
 * @date 2020/10/23 14:38
 * @describe
 */
@Slf4j
@Controller
@CrossOrigin
public class HealthController extends BaseController {

    private final static String character="&";


    /**
     * 血糖检测
     * @param userId 用户id
     * @return
     */
    @PostMapping("/bloodGlucose")
    @ResponseBody
    public CommonResp bloodGlucose(String userId){
        Map<String,String> map=new HashMap<>();
        HttpServletRequest request = ServletUtils.getRequest();
        Map<String, String> stringStringMap = convertRequestParamsToMap(request);

        stringStringMap.put("id", UUID.randomUUID().toString().replaceAll("-",""));
        stringStringMap.put("memberId", userId);

        Map<String,String> bodys=new HashMap<>();
        stringStringMap.forEach((k,v)->{
            if(StringUtils.isNotBlank(v)){
                bodys.put(k,v);
            }
        });


        try {
            String host = "http://idp02.market.alicloudapi.com";
            String path = "/alicloudapi/dailyTest/bloodGlucose";
            String method = "POST";
            String appcode = "94404993dd5b4151a59dbff83d5ed35a";
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + appcode);
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            if (jsonObject.getString("code").equals("0000")) {
                Object data = jsonObject.get("data");
                return success(data);
            } else {
                return failed(jsonObject.getString("msg"));
            }
        }catch (Exception e){
            return failed(e.getMessage());
        }
    }

    /**
     * 体重检测
     * @param userId 用户id
     * @return
     */
    @PostMapping("/bim")
    @ResponseBody
    public CommonResp bmi(String userId){
        log.warn("========================="+userId);
        Map<String,String> map=new HashMap<>();
        HttpServletRequest request = ServletUtils.getRequest();
        Map<String, String> stringStringMap = convertRequestParamsToMap(request);

        stringStringMap.put("id", UUID.randomUUID().toString().replaceAll("-",""));
        stringStringMap.put("memberId", userId);
        if(!stringStringMap.containsKey("testTime")) {
            stringStringMap.put("testTime", DateUtil.getStrFromDate(Calendar.getInstance().getTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        Map<String,String> bodys=new HashMap<>();
        stringStringMap.forEach((k,v)->{
            if(StringUtils.isNotBlank(v)){
                bodys.put(k,v);
            }
        });


        try {
            String host = "http://idp03.market.alicloudapi.com";
            String path = "/alicloudapi/dailyTest/bmi";
            String method = "POST";
            String appcode = "94404993dd5b4151a59dbff83d5ed35a";
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + appcode);
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            if (jsonObject.getString("code").equals("0000")) {
                Object data = jsonObject.get("data");
                return success(data);
            } else {
                return failed(jsonObject.getString("msg"));
            }
        }catch (Exception e){
            return failed(e.getMessage());
        }
    }
    /**
     * 糖尿病
     * @return
     */
    @PostMapping("/diabetes")
    @ResponseBody
    public CommonResp diabetes(String userId){
        log.warn("========================="+userId);
        Map<String,String> map=new HashMap<>();
        HttpServletRequest request = ServletUtils.getRequest();
        Map<String, String> stringStringMap = convertRequestParamsToMap(request);

        stringStringMap.put("testRecordID", UUID.randomUUID().toString().replaceAll("-",""));
        stringStringMap.put("memberID", userId);
        if(!stringStringMap.containsKey("testTime")) {
            stringStringMap.put("testTime", DateUtil.getStrFromDate(Calendar.getInstance().getTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        if(!stringStringMap.containsKey("visitDate")) {
            stringStringMap.put("visitDate", DateUtil.getStrFromDate(Calendar.getInstance().getTime(), "yyyy-MM-dd"));
        }
        Map<String,String> bodys=new HashMap<>();
        stringStringMap.forEach((k,v)->{
            if(StringUtils.isNotBlank(v)){
                bodys.put(k,v);
            }
        });


        try {
            String host = "http://tnb.market.alicloudapi.com";
            String path = "/alicloudapi/chronic/diabetes";
            String method = "POST";
            String appcode = "94404993dd5b4151a59dbff83d5ed35a";
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + appcode);
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            if (jsonObject.getString("code").equals("0000")) {
                Object data = jsonObject.get("data");
                return success(data);
            } else {
                return failed(jsonObject.getString("msg"));
            }
        }catch (Exception e){
            return failed(e.getMessage());
        }
    }

    /**
     * 血压
     * @param highValue
     * @param lowValue
     * @param disease
     * @return
     */
    @PostMapping("/elasticity")
    @ResponseBody
    public CommonResp elasticity(String highValue,String lowValue,String disease ){
        Map<String,String> map=new HashMap<>();
        String paramsValue="highValue="+highValue+"&lowValue="+lowValue+"&disease="+disease;
        try {
            String s = OkHttpUtil.postFormParamsTokenTest("http://dtbp.market.alicloudapi.com/alicloudapi/dailyTest/bloodPressure?" + paramsValue, map, "APPCODE 94404993dd5b4151a59dbff83d5ed35a");
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject.getString("code").equals("0000")) {
                Object data = jsonObject.get("data");
                return success(data);
            } else {
                return failed(jsonObject.getString("msg"));
            }
        }catch (Exception e){
            return failed(e.getMessage());
        }
    }


    private static String buildUrl(String path, Map<String, String> querys) throws UnsupportedEncodingException, UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(path);
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    /**
     * 解析请求中参数
     * @param request
     * @return
     */
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            log.info("支付宝=="+name+"&值==="+values[0]);
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

}

